package com.atos.optical.service.impl;

import cn.hutool.core.util.StrUtil;
import com.atos.optical.Enums.ResponseCodeEnum;
import com.atos.optical.common.BaseServiceImpl;
import com.atos.optical.mapper.SysUserInfoMapper;
import com.atos.optical.model.bo.SysUserInfoBo;
import com.atos.optical.model.po.SysUserInfo;
import com.atos.optical.model.query.SysUserInfoQuery;
import com.atos.optical.service.SysUserInfoService;
import com.atos.optical.common.ServiceException;
import com.atos.optical.utils.CacheUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author wanghra
 * @version 1.0
 * @description
 * @date 2025/8/12
 */
@Slf4j
@Service
public class SysUserInfoServiceImpl extends BaseServiceImpl<SysUserInfoMapper,
        SysUserInfo> implements SysUserInfoService {
    @Autowired
    private SysUserInfoMapper mapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(SysUserInfo entity) {
        check(entity);
        return super.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserInfo(String token, SysUserInfo entity) {
        check(entity);
        boolean update = super.updateById(entity);
        if (update) {
            // 刷新缓存内容
            CacheUtil.put(token, super.getById(entity.getUserId()));
        }
        return update;
    }

    @Override
    public SysUserInfoQuery pageByQuery(SysUserInfoQuery query) {
        query.setOrders(OrderItem.descs("CREATE_TIME", "MODIFY_TIME"));
        mapper.pageByQuery(query);
        return query;
    }

    @Override
    public String validate(SysUserInfoBo entity) {
        if (StrUtil.isBlank(entity.getLoginName())) {
            throw new ServiceException("登录名为空！");
        }
        if (StrUtil.isBlank(entity.getUserPwd())) {
            throw new ServiceException("密码为空！");
        }
        QueryWrapper<SysUserInfo> query = new QueryWrapper<>();
        query.lambda().eq(SysUserInfo::getLoginName, entity.getLoginName())
                .eq(SysUserInfo::getUserPwd, entity.getUserPwd())
                .eq(SysUserInfo::getUserStatus, "1");
        SysUserInfo userInfo = mapper.selectOne(query);
        if (null == userInfo) {
            // 登录失败
            throw new ServiceException(ResponseCodeEnum.VALIDATE_FAIL);
        } else {
            // 登录成功刷新用户登录时间
            UpdateWrapper<SysUserInfo> updateQuery = new UpdateWrapper<>();
            updateQuery.lambda().eq(SysUserInfo::getUserId, userInfo.getUserId())
                    .set(SysUserInfo::getLoginTime, LocalDateTime.now());
            mapper.update(userInfo, updateQuery);
        }
        // 生成token
        String token = UUID.randomUUID().toString().replace("-", "");
        CacheUtil.put(token, userInfo);
        return token;
    }

    private void check(SysUserInfo entity) {
        if (isExistLoginName(entity)) {
            throw new ServiceException("登录名重复！");
        }
    }
    
    private boolean isExistLoginName(SysUserInfo entity) {
        QueryWrapper<SysUserInfo> query = new QueryWrapper<>();
        query.lambda().ne(StrUtil.isNotBlank(entity.getUserId()), SysUserInfo::getUserId, entity.getUserId())
                .eq(SysUserInfo::getLoginName, entity.getLoginName());
        return 0 < mapper.selectCount(query);
    }
}
